import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:m/data/api/index.dart';
import 'package:m/data/module/notice.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPageController extends GetxController {
  IndexProvider api = Get.put<IndexProvider>(IndexProvider());
  late final WebViewController _controller = WebViewController();
  WebViewController get webViewController => _controller;
  Notice? notice;
  Future<void> _loadHtmlFromAssets() async {


    if(notice?.noticeType == (NoticeTypeEnum.notice ) || notice?.noticeType == (NoticeTypeEnum.noticeBoard)){
      loadHtmlStr();
      return;
    } 
    loadWebView();  
  }

  @override
  void onInit() {
    super.onInit();
    debugPrint('WebViewController init');
    var id = Get.parameters['id'];
    debugPrint('WebViewController id: $id');
    if (id != null) {
      api.getNoticeDetail(int.parse(id)).then((value) {
        if (value != null) {
          notice = value;
          _loadHtmlFromAssets();
          // debugPrint(
          //     "WebViewController title: ${value.title}\n ${value.content}");
        }
      });
    }
  }


  void loadHtmlStr()async{
    String css = await rootBundle.loadString('assets/www/styles/style.css');
    String html = ''' <!DOCTYPE html>  <html lang="en"> <head>  <style>  $css 
            .ql-video { width: 100%; height: 1000px; } </style>  </head> <body class="ql-container ql-snow ql-editor"> 
            <h1 style="text-align:center;">${notice?.title}</h1>   ${notice?.content}   </body> </html> ''';
    _controller.loadHtmlString(html);
  }

  loadWebView(){
   _controller
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..loadRequest(Uri.parse(notice!.content));
  }
}
